package com.example.demo.security.provider;

import com.example.demo.configuration.CustomUserDetailsService;
import com.example.demo.security.authentication.CustomUsernamePasswordAuthentication;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.preauth.PreAuthenticatedCredentialsNotFoundException;
import org.springframework.stereotype.Component;

/**
 * describe: 自定义的认证服务
 *
 * @author lianying
 * @date 2020/12/06
 */
@Component
public class CustomUsernamePasswordAuthenticationProvider implements AuthenticationProvider {
    @Autowired
    private CustomUserDetailsService customUserDetailsService;

    @Override
    public Authentication authenticate(Authentication params) throws AuthenticationException {
        System.out.println("--------进入了Provider");
        CustomUsernamePasswordAuthentication authentication = (CustomUsernamePasswordAuthentication) params;
        UserDetails userDetails = customUserDetailsService.loadUserByUsername((String) authentication.getPrincipal());
        if (userDetails.getPassword().equals(params.getCredentials())) {
            authentication.setAuthenticated(true);
            //模拟查库的用户详情信息
            CustomUsernamePasswordAuthentication.UserInfo userInfo=new CustomUsernamePasswordAuthentication.UserInfo();
            userInfo.setAge(20);
            userInfo.setName("li");
            authentication.setUserInfo(userInfo);
            //模拟权限
            authentication.setRoles(userDetails.getAuthorities());
        } else {
            throw new PreAuthenticatedCredentialsNotFoundException("密码错误");
        }
        return authentication;
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return authentication == CustomUsernamePasswordAuthentication.class;
    }
}
